#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdint.h>

#include "debug.h"
#include "os_api.h"
#include "dev_api.h"
#include "cJSON.h"


#define _STACK_SIZE		(1024*3)
static void* _task_stack = NULL;

static OSTaskRef _task_ref = NULL;

static OSATimerRef _task_delete_timer_ref = NULL;

void DeleteTaskByTimer(UINT32 id)
{
    OSA_STATUS status;

    if(_task_ref)
    {
        status = OSATaskDelete(_task_ref);
        ASSERT(status == OS_SUCCESS);
        _task_ref = NULL;
	   
        if(_task_stack)
        {
            free(_task_stack);
            _task_stack = NULL;
        }
    }

    OSATimerDelete (_task_delete_timer_ref);
}


// 解析 JSON 字符串示例
void parseJsonExample(void) 
{
    const char *jsonStr = "{\"name\":\"John\",\"age\":30,\"isStudent\":true}";
    cJSON *root = cJSON_Parse(jsonStr);
    if (root) {
        cJSON *name = cJSON_GetObjectItem(root, "name");
        cJSON *age = cJSON_GetObjectItem(root, "age");
        cJSON *isStudent = cJSON_GetObjectItem(root, "isStudent");

        if (name && age && isStudent) {
            LOG_PRINTF("Name: %s\n", name->valuestring);
            LOG_PRINTF("Age: %d\n", age->valueint);
            LOG_PRINTF("Is Student: %s\n", isStudent->type == cJSON_False? "false" : "true");
        }
        cJSON_Delete(root);
    }
}

// 创建 JSON 字符串示例
void createJsonExample(void) 
{
    cJSON *root = cJSON_CreateObject();
    if (root) {
        cJSON_AddStringToObject(root, "name", "Alice");
        cJSON_AddNumberToObject(root, "age", 25);
        cJSON_AddBoolToObject(root, "isStudent", 0/*false*/);

        char *jsonStr = cJSON_Print(root);
        if (jsonStr) {
            LOG_PRINTF("Created JSON: %s\n", jsonStr);
            free(jsonStr);
        }
        cJSON_Delete(root);
    }
}

static void _task(void *ptr)
{
    parseJsonExample();
    createJsonExample();
	
	OSATimerCreate(&_task_delete_timer_ref);
	OSATimerStart(_task_delete_timer_ref, 400, 0, DeleteTaskByTimer, 0);
}


int main(void)
{	
    int ret;

	_task_stack = malloc(_STACK_SIZE);
    ASSERT(_task_stack != NULL);
	
    ret = OSATaskCreate(&_task_ref, _task_stack, _STACK_SIZE, 100, "_task", _task, NULL);
    ASSERT(ret == OS_SUCCESS);
	
	return 0;
}